<?php
/**
 * 团购模型
 * Created by Sublime Text 3.
 * @authors Rejeo (rejeo@qq.com)
 * @date    2018-05-01 15:09:16
 */
namespace app\common\model;

use app\common\model\BaseModel;

class Deal extends BaseModel
{
    // 搜索
    public function getNormalDeals($data=[])
    {
        // $data['status'] = 1;
        $data['status'] = ['gt', -1];
        $order = ['id'=>'desc'];
        $field = ['id','name','category_id','city_id','buy_count','status','start_time','end_time','create_time'];
        $res = $this->field($field)
                    ->where($data)
                    ->order($order)
                    ->paginate();
        return $res;
    }

    /**
     * 根据分类和城市 来获取 商品数据
     * @param  integer  $id      栏目分类id
     * @param  integer  $cityId  城市id
     * @param  integer  $limit   获取数目
     * @return mixed
     */
    public function getNormalDealByCategoryCityId($id, $cityId, $limit=10)
    {
        $data = [
            'end_time'    => ['gt', time()],
            'category_id' => $id,
            'city_id'     => $cityId,
            'status'      => 1,
        ];
        $order = ['listorder'=>'desc','id'=>'desc'];

        $res = $this->where($data)->order($order);
        if ($limit) {
            $res = $res->limit($limit);
        }
        return $res->select();
    }

    /**
     * 根据条件，排序商品
     * @param  array    $data   排序条件
     * @param  string   $orders 排序方式
     * @return resource
     */
    public function getDealByConditions($data, $orders)
    {
        $order['id'] = 'desc';
        $datas[] = "status=1";
        $datas[] = "end_time>".time();
        if (!empty($orders['order_sales'])) {
            $order['buy_count'] = 'desc';
        }
        if (!empty($orders['order_price'])) {
            $order['current_price'] = 'desc';
        }
        if (!empty($orders['order_time'])) {
            $order['create_time'] = 'desc';
        }
        // 处理商品相关的方法
        // find_in_set mysql 自带函数，查找某个字符串是否在某个字段中第一次出现的位置
        // 返回查找到的位置，找不到返回0，初始位置1开头
        // example:SELECT FIND_IN_SET('a','a,c,d,b');
        // 类似于php中的strpos
        if (!empty($data['se_category_id'])) {
            $dates[] = "find_in_set(".$data['se_category_id'].", `se_category_id`)";
        }
        if (!empty($data['category_id'])) {
            $dates[] = "category_id='".$data['category_id']."'";
        }
        if (!empty($data['city_id'])) {
            $dates[] = "city_id='".$data['city_id']."'";
        }
        $res = $this->where(implode('AND',$datas))->order($order)->select();
        return $res;
    }

    public function updateByCountById($id, $buyCount)
    {
        // if (empty($id) || empty($buyCount)) {
        //     return '数据提交有误！';
        // }
        return $this->where(['id'=>$id])->setInc('buy_count', $buyCount);
    }
}
